package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.api.db.*;
import com.tanhua.api.mongdb.FriendApi;
import com.tanhua.api.mongdb.RecommentApi;
import com.tanhua.api.mongdb.UserLikeApi;
import com.tanhua.api.mongdb.VisitorApi;
import com.tanhua.domain.UserHolder;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Friend;
import com.tanhua.domain.mogo.UserLike;
import com.tanhua.domain.mogo.Visitors;
import com.tanhua.domain.vo.*;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmStemplate;
import com.tanhua.utils.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private SmStemplate smStemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private RecommentApi recommentApi;


    public ResponseEntity save(User user){
        Long id = userApi.save(user);
        return ResponseEntity.ok(id);
    }


    public ResponseEntity findByPhone(String phone){
        User user = userApi.findByPhone(phone);
        return ResponseEntity.ok(user);
    }


    public ResponseEntity login(String phone) throws ClientException {
        //String code = RandomUtil.randomNumbers(6);
        String code ="123456";
        //smStemplate.sendSms(phone,code);
        // 将验证码放入redis中
        stringRedisTemplate.opsForValue().set("SMS_CODE_"+phone,code,10, TimeUnit.MINUTES);
        System.out.println("验证码已发送："+code);
        return ResponseEntity.ok(null);
    }


    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //注册、登录
    public ResponseEntity loginVerification(String phone, String yzm) {
        // 1 判断验证码
        String code = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if(!StrUtil.equals(yzm,code)){
            // 不一致
            return ResponseEntity.status(500).body("验证码错误");
        }

        //删除redis中的验证码（优化）
        stringRedisTemplate.delete("SMS_CODE_" + phone);



        //老用户
        Boolean flag=false;
        // 2 根据手机号做查询
        User user = userApi.findByPhone(phone);

        if(user==null){
            // 3 不存在
            user = new User();
            user.setPassword(SecureUtil.md5("123456"));
            user.setPhone(phone);
            Long id = userApi.save(user);   //注册探花用户
            huanXinTemplate.register(id);   //注册成环信用户
            user.setId(id);
            //新用户
            flag=true;
        }

        //优化1：对老/新用户的数据做加密生成一串字符串（token）
        String token = JwtUtil.createToken(user.getPhone(), user.getId(), "tanhua");
        //优化2：将token和用户数据放入redis中
        String user_json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1,TimeUnit.DAYS);
        // 5 返回
        Map map=new HashMap();
        //优化3：将token响应给app保存
        map.put("token",token);
        map.put("isNew",flag);

        //生产者--数据生产到中间件中
        Map<String,String> mqMp=new HashMap<>();
        mqMp.put("userId",user.getId().toString());
        mqMp.put("type",flag?"0102":"0101");
        mqMp.put("logTime", DateUtil.format(new Date(),"yyyy-MM-dd"));

        rocketMQTemplate.convertAndSend("tanhua-log",mqMp);

        return ResponseEntity.ok(map);
    }

    public ResponseEntity loginReginfo(UserInfo userInfo, String token) {

        //根据token从redis获取当前登录用户
        User user=findUserByToken(token);
        userInfo.setId(user.getId());
        //此时是没有头像地址的
        userInfoApi.save(userInfo);
        return ResponseEntity.ok(null);
    }

    //根据token从redis获取当前登录用户
    public User findUserByToken(String token) {
        String user_json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        User user = JSON.parseObject(user_json, User.class);
        //追加一天
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1,TimeUnit.DAYS);
        return user;
    }

    public ResponseEntity loginReginfoimg(MultipartFile headPhoto, String token) throws IOException {
        //1 判断人脸识别
        boolean flag = aipFaceTemplate.detect(headPhoto.getBytes());
        if(!flag){
            //识别失败
            return ResponseEntity.status(500).body("人脸识别失败！！！");
        }
        //2 上传图片到oss 记录地址
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //3 根据token获取登录用户
        User user = findUserByToken(token);
        //4 设置userInfo的id且根据id做修改
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(imgUrl);
        userInfo.setCoverPic(imgUrl);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        //5 返回
        return ResponseEntity.ok(null);
    }

    //当前登录用户的数据回显
    public ResponseEntity findUserInfoVo(Long id) {

        // 根据id做查询
        UserInfo userInfo=userInfoApi.findByUser(id);
        //将userInfo的数据给userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        //对象数据转换
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return ResponseEntity.ok(userInfoVo);
    }

    public ResponseEntity updateInfo(String token, UserInfo userInfo) {
        User user = findUserByToken(token);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }


    @Reference
    private QuestionApi questionApi;
    @Reference
    private SettingsApi settingsApi;

    public ResponseEntity userSettings() {
        // 1 获取登录用户的id
        User user = UserHolder.findUser();
        // 2 根据id做问题查询
        Question question = questionApi.findByQuestion(user.getId());
        // 3 根据id做喜好通知查询
        Settings settings = settingsApi.findBySettings(user.getId());
        // 4 自定义app需要的vo进行封装返回
        SettingsVo vo = new SettingsVo();
        vo.setId(user.getId());
        vo.setPhone(user.getPhone());
        if(question!=null){
            vo.setStrangerQuestion(question.getStrangerQuestion());
        }
        if(settings!=null){
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }

        return ResponseEntity.ok(vo);

    }

    public ResponseEntity saveOrUpdateQuestions(String content, Long id) {

        // 先根据id做查询
        Question question = questionApi.findByQuestion(id);
        if(question==null){
            //新增
            question=new Question();
            question.setStrangerQuestion(content);
            question.setUserId(id);
            questionApi.save(question);
        }else{
            //修改
            question.setStrangerQuestion(content);
            questionApi.update(question);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveOrUpdateSettings(Settings setting, Long id) {

        // 先根据id做查询
        Settings settings = settingsApi.findBySettings(id);
        if(settings==null){
            //新增
            setting.setUserId(id);
            settingsApi.save(setting);
        }else{

            //修改
            settings.setGonggaoNotification(setting.getGonggaoNotification());
            settings.setLikeNotification(setting.getLikeNotification());
            settings.setPinglunNotification(setting.getPinglunNotification());
            settingsApi.update(settings);
        }

        return ResponseEntity.ok(null);

    }


    @Reference
    private BlackListApi blackListApi;

    //分页做查询
    public ResponseEntity findBlacklist(Integer page, Integer pagesize, Long id) {
        IPage pagebean = blackListApi.findBlacklist(page, pagesize, id);
        //创建app需要的vo
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,pagebean.getTotal(),pagebean.getRecords());

        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity deleteBlack(Long uid, Long id) {
        blackListApi.deleteBlack(uid,id);
        return ResponseEntity.ok(null);
    }


    @Reference
    private FriendApi friendApi;

    @Reference
    private UserLikeApi userLikeApi;

    public ResponseEntity findCounts() {

        // 1 统计互相喜欢的
        Long eachLoveCount=friendApi.findeachLoveCount(UserHolder.findUser().getId());
        // 2 统计喜欢的
        Long loveCount=userLikeApi.findloveCount(UserHolder.findUser().getId());
        //3 统计粉丝
        Long fanCount=userLikeApi.findfanCount(UserHolder.findUser().getId());
        //4 封装vo返回
        CountsVo countsVo = new CountsVo(eachLoveCount,loveCount,fanCount);
        return ResponseEntity.ok(countsVo);
    }

    @Reference
    private VisitorApi visitorApi;

    public ResponseEntity findTypePage(Integer page, Integer pagesize, Integer type) {

        PageBeanVo pageBean=null;

        List<UserLikeListVo> voList=new ArrayList<>();
        switch (type){
            case 1:{
                // 查询相互喜欢的数据
                pageBean=friendApi.findeachLovePage(page,pagesize,UserHolder.findUser().getId());
                List<Friend> items = (List<Friend>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Friend friend : items) {
                            //userInfo
                        UserInfo userInfo = userInfoApi.findByUser(friend.getFriendId());
                            //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.findUser().getId(), friend.getFriendId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 2:{
                // 查询喜欢的数据
                pageBean=userLikeApi.findeachLovePage(page,pagesize,UserHolder.findUser().getId());
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findByUser(userLike.getLikeUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.findUser().getId(), userLike.getLikeUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 3:{
                // 查询粉丝的数据
                pageBean=userLikeApi.findfanPage(page,pagesize,UserHolder.findUser().getId());
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findByUser(userLike.getUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.findUser().getId(), userLike.getUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 4:{
                // 查询历史访客的数据
                pageBean= visitorApi.findHistoryPage(page,pagesize,UserHolder.findUser().getId());
                List<Visitors> items = (List<Visitors>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Visitors visitors : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findByUser(visitors.getVisitorUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.findUser().getId(), visitors.getVisitorUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
        }

        pageBean.setItems(voList);

        return ResponseEntity.ok(pageBean);
    }

    public ResponseEntity fansToFriend(Long fansId) {

        // 1 friend中多2条数据（增）
        friendApi.contacts(fansId,UserHolder.findUser().getId());

        //2 user_like少一条数据（删）
        userLikeApi.removeFans(fansId,UserHolder.findUser().getId());
        return ResponseEntity.ok(null);

    }

    public ResponseEntity FriendTofans(Long loveId) {

        // 判断是互相好友的取消还是喜欢的取消
        Boolean flg=friendApi.isFriend(UserHolder.findUser().getId(),loveId);
        if(flg){
            // 互相好友-->删除2条friend数据 userLike添加一条粉丝数据
            friendApi.removeFriend(UserHolder.findUser().getId(),loveId);
            userLikeApi.addUserLike(UserHolder.findUser().getId(),loveId);
        }else{
            // 喜欢--->自己删除该用户 不做舔狗
            userLikeApi.removeFans(UserHolder.findUser().getId(),loveId);
        }

        return ResponseEntity.ok(null);


    }
}
